#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
ComfyUI 依赖管理工具 - PyQt6 GUI版本
跨平台图形界面依赖管理工具
"""

import sys
import os
import threading
import subprocess
from pathlib import Path
from datetime import datetime

# PyQt6 导入
from PyQt6.QtWidgets import (
    QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
    QPushButton, QTextEdit, QLabel, QProgressBar, QTabWidget,
    QGroupBox, QGridLayout, QMessageBox, QFileDialog, QComboBox,
    QCheckBox, QSpinBox, QLineEdit, QSplitter, QFrame
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer
from PyQt6.QtGui import QFont, QIcon, QPalette, QColor

# 导入统一的环境配置
from env_setup import setup_environment, ENV_CONFIG, COMFYUI_DIR

# 使用统一的环境配置
ENV_CONFIG = setup_environment()

# 添加项目根目录到路径
project_root = Path(__file__).parent.parent.parent
sys.path.insert(0, str(project_root))

from depend_manager import DependencyManager

class WorkerThread(QThread):
    """后台工作线程"""
    progress = pyqtSignal(str)
    finished = pyqtSignal(bool, str)
    
    def __init__(self, task_func, *args, **kwargs):
        super().__init__()
        self.task_func = task_func
        self.args = args
        self.kwargs = kwargs
    
    def run(self):
        try:
            result = self.task_func(*self.args, **self.kwargs)
            self.finished.emit(True, str(result))
        except Exception as e:
            self.finished.emit(False, str(e))

class ComfyUIDependencyGUI(QMainWindow):
    def __init__(self):
        super().__init__()
        self.manager = None
        self.worker_thread = None
        self.init_ui()
        self.init_manager()
        
    def init_ui(self):
        """初始化用户界面"""
        self.setWindowTitle("ComfyUI 依赖管理工具")
        self.setGeometry(100, 100, 1000, 700)
        
        # 设置样式
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f0f0f0;
            }
            QGroupBox {
                font-weight: bold;
                border: 2px solid #cccccc;
                border-radius: 5px;
                margin-top: 1ex;
                padding-top: 10px;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px 0 5px;
            }
            QPushButton {
                background-color: #4CAF50;
                border: none;
                color: white;
                padding: 8px 16px;
                text-align: center;
                font-size: 14px;
                border-radius: 4px;
                min-width: 100px;
            }
            QPushButton:hover {
                background-color: #45a049;
            }
            QPushButton:pressed {
                background-color: #3d8b40;
            }
            QPushButton:disabled {
                background-color: #cccccc;
                color: #666666;
            }
            QTextEdit {
                border: 1px solid #cccccc;
                border-radius: 4px;
                padding: 5px;
                font-family: 'Consolas', 'Monaco', monospace;
                font-size: 12px;
            }
            QProgressBar {
                border: 1px solid #cccccc;
                border-radius: 4px;
                text-align: center;
            }
            QProgressBar::chunk {
                background-color: #4CAF50;
                border-radius: 3px;
            }
        """)
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 标题
        title_label = QLabel("ComfyUI 依赖管理工具")
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_label.setStyleSheet("""
            font-size: 24px;
            font-weight: bold;
            color: #333333;
            margin: 10px;
        """)
        main_layout.addWidget(title_label)
        
        # 创建标签页
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        
        # 添加各个标签页
        self.create_main_tab()
        self.create_advanced_tab()
        self.create_log_tab()
        
        # 状态栏
        self.statusBar().showMessage("就绪")
        
    def create_main_tab(self):
        """创建主标签页"""
        main_tab = QWidget()
        layout = QVBoxLayout(main_tab)
        
        # 系统信息组
        info_group = QGroupBox("系统信息")
        info_layout = QGridLayout(info_group)
        
        self.python_path_label = QLabel("Python路径: 检测中...")
        self.comfyui_path_label = QLabel("ComfyUI路径: 检测中...")
        self.backup_path_label = QLabel("备份路径: 检测中...")
        
        info_layout.addWidget(QLabel("Python解释器:"), 0, 0)
        info_layout.addWidget(self.python_path_label, 0, 1)
        info_layout.addWidget(QLabel("ComfyUI目录:"), 1, 0)
        info_layout.addWidget(self.comfyui_path_label, 1, 1)
        info_layout.addWidget(QLabel("备份目录:"), 2, 0)
        info_layout.addWidget(self.backup_path_label, 2, 1)
        
        layout.addWidget(info_group)
        
        # 主要操作组
        actions_group = QGroupBox("主要操作")
        actions_layout = QGridLayout(actions_group)
        
        self.install_btn = QPushButton("安装/更新依赖")
        self.install_btn.clicked.connect(self.install_dependencies)
        
        self.check_btn = QPushButton("检查依赖状态")
        self.check_btn.clicked.connect(self.check_dependencies)
        
        self.backup_btn = QPushButton("备份当前依赖")
        self.backup_btn.clicked.connect(self.backup_dependencies)
        
        self.restore_btn = QPushButton("还原依赖")
        self.restore_btn.clicked.connect(self.restore_dependencies)
        
        actions_layout.addWidget(self.install_btn, 0, 0)
        actions_layout.addWidget(self.check_btn, 0, 1)
        actions_layout.addWidget(self.backup_btn, 1, 0)
        actions_layout.addWidget(self.restore_btn, 1, 1)
        
        layout.addWidget(actions_group)
        
        # 进度条
        self.progress_bar = QProgressBar()
        self.progress_bar.setVisible(False)
        layout.addWidget(self.progress_bar)
        
        # 输出区域
        output_group = QGroupBox("操作输出")
        output_layout = QVBoxLayout(output_group)
        
        self.output_text = QTextEdit()
        self.output_text.setMaximumHeight(200)
        output_layout.addWidget(self.output_text)
        
        layout.addWidget(output_group)
        
        self.tab_widget.addTab(main_tab, "主要功能")
        
    def create_advanced_tab(self):
        """创建高级标签页"""
        advanced_tab = QWidget()
        layout = QVBoxLayout(advanced_tab)
        
        # 高级操作组
        advanced_group = QGroupBox("高级操作")
        advanced_layout = QGridLayout(advanced_group)
        
        self.uninstall_btn = QPushButton("卸载所有依赖")
        self.uninstall_btn.clicked.connect(self.uninstall_dependencies)
        self.uninstall_btn.setStyleSheet("background-color: #f44336;")
        
        self.clean_btn = QPushButton("清理缓存")
        self.clean_btn.clicked.connect(self.clean_cache)
        
        self.privileges_btn = QPushButton("检查权限")
        self.privileges_btn.clicked.connect(self.check_privileges)
        
        advanced_layout.addWidget(self.uninstall_btn, 0, 0)
        advanced_layout.addWidget(self.clean_btn, 0, 1)
        advanced_layout.addWidget(self.privileges_btn, 1, 0)
        
        layout.addWidget(advanced_group)
        
        # 设置组
        settings_group = QGroupBox("设置")
        settings_layout = QGridLayout(settings_group)
        
        settings_layout.addWidget(QLabel("Python路径:"), 0, 0)
        self.python_path_edit = QLineEdit()
        self.python_path_edit.setPlaceholderText("自动检测")
        settings_layout.addWidget(self.python_path_edit, 0, 1)
        
        settings_layout.addWidget(QLabel("ComfyUI路径:"), 1, 0)
        self.comfyui_path_edit = QLineEdit()
        self.comfyui_path_edit.setPlaceholderText("自动检测")
        settings_layout.addWidget(self.comfyui_path_edit, 1, 1)
        
        layout.addWidget(settings_group)
        
        layout.addStretch()
        self.tab_widget.addTab(advanced_tab, "高级功能")
        
    def create_log_tab(self):
        """创建日志标签页"""
        log_tab = QWidget()
        layout = QVBoxLayout(log_tab)
        
        # 日志控制
        log_control_layout = QHBoxLayout()
        
        self.clear_log_btn = QPushButton("清空日志")
        self.clear_log_btn.clicked.connect(self.clear_log)
        
        self.save_log_btn = QPushButton("保存日志")
        self.save_log_btn.clicked.connect(self.save_log)
        
        log_control_layout.addWidget(self.clear_log_btn)
        log_control_layout.addWidget(self.save_log_btn)
        log_control_layout.addStretch()
        
        layout.addLayout(log_control_layout)
        
        # 日志显示
        self.log_text = QTextEdit()
        layout.addWidget(self.log_text)
        
        self.tab_widget.addTab(log_tab, "日志")
        
    def init_manager(self):
        """初始化依赖管理器"""
        try:
            # 查找ComfyUI目录
            comfyui_path = self.find_comfyui_dir()
            if comfyui_path:
                self.manager = DependencyManager(str(comfyui_path))
                self.update_system_info()
                self.log_message("✅ 依赖管理器初始化成功")
            else:
                self.log_message("❌ 未找到ComfyUI目录")
        except Exception as e:
            self.log_message(f"❌ 初始化失败: {e}")
            
    def find_comfyui_dir(self):
        """自动查找 ComfyUI 目录（使用统一配置）"""
        comfyui_dir = COMFYUI_DIR
        if comfyui_dir.exists():
            return comfyui_dir
        # 兼容大小写
        base = ENV_CONFIG['PROJECT_ROOT']
        for d in base.iterdir():
            if d.is_dir() and d.name.lower() == "comfyui":
                return d
        return None
        
    def update_system_info(self):
        """更新系统信息显示"""
        if self.manager:
            self.python_path_label.setText(self.manager.python_path)
            self.comfyui_path_label.setText(str(self.manager.workspace_path))
            self.backup_path_label.setText(str(self.manager.backup_dir))
            
    def log_message(self, message):
        """添加日志消息"""
        timestamp = datetime.now().strftime("%H:%M:%S")
        log_entry = f"[{timestamp}] {message}"
        
        self.output_text.append(log_entry)
        self.log_text.append(log_entry)
        
        # 自动滚动到底部
        self.output_text.verticalScrollBar().setValue(
            self.output_text.verticalScrollBar().maximum()
        )
        
    def run_task(self, task_func, task_name):
        """运行后台任务"""
        if self.worker_thread and self.worker_thread.isRunning():
            QMessageBox.warning(self, "警告", "已有任务正在运行，请等待完成")
            return
            
        self.progress_bar.setVisible(True)
        self.progress_bar.setRange(0, 0)  # 不确定进度
        self.log_message(f"🚀 开始执行: {task_name}")
        
        self.worker_thread = WorkerThread(task_func)
        self.worker_thread.finished.connect(
            lambda success, result: self.task_finished(success, result, task_name)
        )
        self.worker_thread.start()
        
    def task_finished(self, success, result, task_name):
        """任务完成回调"""
        self.progress_bar.setVisible(False)
        
        if success:
            self.log_message(f"✅ {task_name} 完成")
            self.statusBar().showMessage(f"{task_name} 完成")
        else:
            self.log_message(f"❌ {task_name} 失败: {result}")
            self.statusBar().showMessage(f"{task_name} 失败")
            
    def install_dependencies(self):
        """安装依赖"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        reply = QMessageBox.question(
            self, "确认", "确定要安装/更新依赖吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.run_task(self.manager.install_dependencies, "安装依赖")
            
    def check_dependencies(self):
        """检查依赖"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        self.run_task(self.manager.check_dependencies, "检查依赖")
        
    def backup_dependencies(self):
        """备份依赖"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        self.run_task(self.manager.backup_dependencies, "备份依赖")
        
    def restore_dependencies(self):
        """还原依赖"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        # 选择备份文件
        backup_file, _ = QFileDialog.getOpenFileName(
            self, "选择备份文件", str(self.manager.backup_dir),
            "备份文件 (*.txt);;所有文件 (*)"
        )
        
        if backup_file:
            self.run_task(
                lambda: self.manager.restore_dependencies(backup_file),
                "还原依赖"
            )
            
    def uninstall_dependencies(self):
        """卸载依赖"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        reply = QMessageBox.warning(
            self, "警告", 
            "此操作将卸载所有第三方依赖库！\n确定要继续吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.run_task(self.manager.uninstall_dependencies, "卸载依赖")
            
    def clean_cache(self):
        """清理缓存"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        self.run_task(self.manager.clean_cache, "清理缓存")
        
    def check_privileges(self):
        """检查权限"""
        if not self.manager:
            QMessageBox.warning(self, "错误", "依赖管理器未初始化")
            return
            
        self.run_task(self.manager.check_privileges, "检查权限")
        
    def clear_log(self):
        """清空日志"""
        self.output_text.clear()
        self.log_text.clear()
        
    def save_log(self):
        """保存日志"""
        file_path, _ = QFileDialog.getSaveFileName(
            self, "保存日志", f"comfyui_dependency_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt",
            "文本文件 (*.txt);;所有文件 (*)"
        )
        
        if file_path:
            try:
                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(self.log_text.toPlainText())
                QMessageBox.information(self, "成功", f"日志已保存到: {file_path}")
            except Exception as e:
                QMessageBox.critical(self, "错误", f"保存失败: {e}")

def main():
    """主函数"""
    app = QApplication(sys.argv)
    
    # 设置应用信息
    app.setApplicationName("ComfyUI 依赖管理工具")
    app.setApplicationVersion("2.0.0")
    app.setOrganizationName("ComfyUI")
    
    # 创建主窗口
    window = ComfyUIDependencyGUI()
    window.show()
    
    # 运行应用
    sys.exit(app.exec())

if __name__ == "__main__":
    main() 